﻿using System.Text;
using Klear.Library.Helpers;
using Newtonsoft.Json.Linq;

namespace Klear.Library.Services;

public class WeatherService
{
    public async Task<string> GetWeather()
    {
        
        string res = "查询失败";
        using (HttpClient client = new HttpClient())
        {
            HttpContent content = new StringContent(AccessKeyStorage.WEATHER_BODY, Encoding.UTF8,
                "application/x-www-form-urlencoded");
            try
            {
                HttpResponseMessage response = await client.PostAsync(AccessKeyStorage.WEATHER_URL, content);
                response.EnsureSuccessStatusCode();

                res = await response.Content.ReadAsStringAsync();
                JObject responseMsg = JObject.Parse(res);
                string innerJsonText = responseMsg["result"]?.ToString();
                if (string.IsNullOrEmpty(innerJsonText))
                {
                    throw new Exception("Inner JSON text is null or empty.");
                }

                JObject innerJson = JObject.Parse(innerJsonText);
                string week=innerJson["week"]?.ToString() ?? "未知";
                res = innerJson["weather"]?.ToString() ?? "加载失败";
                res = res+"("+week+")";

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred: " + ex.Message);
            }
            return res;
        }
    }
}